package com.igeek.boot.config;

import cn.hutool.json.JSONUtil;

import com.igeek.boot.result.Result;
import com.igeek.boot.utils.WebUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * TODO
 *
 * @author chemin
 * @since 2024/1/4
 */
@Configuration
public class SecurityHandler {

    //认证失败处理器  401
    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint(){
        AuthenticationEntryPoint authenticationEntryPoint = new AuthenticationEntryPoint() {
            @Override
            public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                Result result = new Result(false , "认证失败，请重新登录" , authException.getMessage());
                WebUtils.renderString(response , JSONUtil.toJsonStr(result));
            }
        };
        return authenticationEntryPoint;
    }

    //授权失败处理器  403
    @Bean
    public AccessDeniedHandler accessDeniedHandler(){
        AccessDeniedHandler accessDeniedHandler = new AccessDeniedHandler() {
            @Override
            public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                Result result = new Result(false , "您的权限不足" , accessDeniedException.getMessage());
                WebUtils.renderString(response , JSONUtil.toJsonStr(result));
            }
        };
        return accessDeniedHandler;
    }

}
